<?php

use Phalcon\Mvc\Controller;

date_default_timezone_set('Asia/Bangkok');

class ControllerBase extends Controller {

    public function initialize() {
        $identity = $this->auth->getIdentity();
        if ($identity) {
            $user = Users::findFirstById($identity['id']);
            if (!$user) {
                $this->auth->remove();
            } else {
                $controller = $this->router->getControllerName();
                $controller = $controller ? $controller : 'index';
                if (!in_array($controller, array('auth', 'index', 'error'))) {
                    $controller = $this->router->getControllerName();
                    $permission = Permissions::findFirstByController($controller);
                    if ($permission && $permission->roles) {
                        if (!in_array($identity['role'], explode(',', $permission->roles))) {
                            $this->dispatcher->forward(array(
                                'controller' => 'error',
                                'action' => 'permission',
                            ));
                        }
                    } else {
                        $this->dispatcher->forward(array(
                            'controller' => 'error',
                            'action' => 'permission',
                        ));
                    }
                }
            }
        }
    }

}
